<?php

namespace app\api\service;


use app\api\model\Resources as ResourcesModel;
use think\Exception;

class Resources
{
    public function add($type, $content)
    {
        if ($type == 'image') {
            $r = [];
            foreach ($content as $key => $file) {
                $info = $file->validate(['size' => 1024 * 1000 * 3])
                    ->move(ROOT_PATH . 'public' . DS . 'uploads');
                if (!$info) {
                    throw new Exception('第' . ($key + 1) . '个' . $file->getError());
                }
                $r[] = $info->getSaveName();
            }
            $content = json_encode($r);
        }
        $data = [
            'type'         => $type,
            'content'      => $content,
            'created_time' => time()
        ];
        (new ResourcesModel)->insert($data);
    }

    public function get($type, $search, $page, $pageSize)
    {
        $query = (new ResourcesModel)
            ->where('type', $type)
            ->whereNull('deleted_time')
            ->order('id', 'desc')
            ->limit(($page - 1) * $pageSize, $pageSize);
        if (!empty($search['keyword'])) {
            $query->whereLike('content', '%' . $search['keyword'] . '%');
        }
        if (!empty($search['date'])) {
            $date    = array_map('strtotime', $search['date']);
            $date[1] += 86399;
            $query->whereBetween('created_time', $date);
        }
        $data = $query->select();
        foreach ($data as &$val) {
            $val            = $val->toArray();
            $val['created'] = date('Y-m-d H:i', $val['created_time']);
            if ($val['type'] == 'image') {
                $val['content'] = json_decode($val['content'], true);
                foreach ($val['content'] as &$img) {
                    if (substr($img, 0, 4) != 'http') {
                        $img = request()->domain() . '/uploads/' . $img;
                    }
                }
                unset($img);
            }
        }

        return ['list' => $data, 'lastPage' => count($data) != $pageSize];
    }

    public function del($type, $ids)
    {
        (new ResourcesModel)->where('type', $type)->whereIn('id', $ids)->update(['deleted_time' => time()]);
    }
}
